#include "reorderservice.h"
#include "usermanager.h"
#include <QDebug>
#include <QUuid>
#include <QThread>
#include <QCoreApplication>

namespace RestaurantSystem {

// 静态成员初始化
ReorderService* ReorderService::s_instance = nullptr;

// 默认配置常量
const int ReorderService::DEFAULT_MAX_RETRIES = 3;
const int ReorderService::DEFAULT_BATCH_SIZE = 10;
const int ReorderService::DEFAULT_CACHE_TIMEOUT_MINUTES = 5;

ReorderService::ReorderService(QObject* parent)
    : QObject(parent)
    , m_orderManager(nullptr)
    , m_menuManager(nullptr)
    , m_errorHandler(nullptr)
    , m_maxRetries(DEFAULT_MAX_RETRIES)
    , m_batchSize(DEFAULT_BATCH_SIZE)
    , m_cacheTimeoutMinutes(DEFAULT_CACHE_TIMEOUT_MINUTES)
    , m_cacheEnabled(true)
    , m_enableAsyncProcessing(false)
    , m_totalProcessedOrders(0)
    , m_totalSuccessfulOrders(0)
    , m_totalPartialOrders(0)
    , m_totalFailedOrders(0)
    , m_isInitialized(false)
    , m_isProcessing(false)
    , m_isCancelled(false)
    , m_cacheCleanupTimer(nullptr)
{
    // 创建缓存清理定时器
    m_cacheCleanupTimer = new QTimer(this);
    m_cacheCleanupTimer->setInterval(m_cacheTimeoutMinutes * 60 * 1000); // 转换为毫秒
    connect(m_cacheCleanupTimer, &QTimer::timeout, this, &ReorderService::onCacheCleanupTimer);
}

ReorderService::~ReorderService()
{
    if (m_cacheCleanupTimer) {
        m_cacheCleanupTimer->stop();
    }
}

ReorderService& ReorderService::instance()
{
    if (!s_instance) {
        s_instance = new ReorderService();
    }
    return *s_instance;
}

bool ReorderService::initialize()
{
    QMutexLocker locker(&m_mutex);
    
    if (m_isInitialized) {
        return true;
    }
    
    try {
        // 获取管理器实例
        m_orderManager = &OrderManager::instance();
        m_menuManager = &MenuManager::instance();
        m_errorHandler = &ErrorHandler::instance();
        
        if (!m_orderManager || !m_menuManager || !m_errorHandler) {
            logOperation("初始化", "管理器实例获取失败");
            return false;
        }
        
        // 连接菜单管理器信号以更新缓存
        connect(m_menuManager, &MenuManager::menuItemUpdated, 
                this, &ReorderService::onMenuItemUpdated);
        connect(m_menuManager, &MenuManager::stockUpdated, 
                this, &ReorderService::onStockUpdated);
        
        // 启动缓存清理定时器
        if (m_cacheEnabled) {
            m_cacheCleanupTimer->start();
        }
        
        m_isInitialized = true;
        logOperation("初始化", "ReorderService初始化成功");
        
        return true;
    } catch (const std::exception& e) {
        QString error = QString("ReorderService初始化异常: %1").arg(e.what());
        logOperation("初始化", error);
        m_errorHandler->handleError(ErrorLevel::ERROR, error);
        return false;
    }
}

ReorderResult ReorderService::processReorder(const Order& originalOrder, const QString& currentUserId)
{
    QMutexLocker locker(&m_mutex);
    
    ReorderResult result;
    result.processTime = QDateTime::currentDateTime();
    
    if (!m_isInitialized) {
        result.errorCode = ReorderErrorCode::SYSTEM_ERROR;
        result.message = "服务未初始化";
        logOperation("重新下单", QString("服务未初始化，订单ID: %1").arg(originalOrder.id));
        return result;
    }
    
    if (m_isProcessing) {
        result.errorCode = ReorderErrorCode::SYSTEM_ERROR;
        result.message = "服务正忙，请稍后重试";
        return result;
    }
    
    m_isProcessing = true;
    m_isCancelled = false;
    
    emit reorderStarted(originalOrder.id, currentUserId);
    
    try {
        // 1. 验证用户权限
        if (!validateUserPermission(originalOrder, currentUserId)) {
            result.errorCode = ReorderErrorCode::USER_NOT_LOGIN;
            result.message = "用户权限验证失败";
            logOperation("重新下单", QString("权限验证失败，订单ID: %1, 用户ID: %2")
                        .arg(originalOrder.id).arg(currentUserId));
            m_isProcessing = false;
            emit reorderFailed(originalOrder.id, result.message);
            return result;
        }
        
        // 2. 验证订单有效性
        if (!validateOrderValidity(originalOrder)) {
            result.errorCode = ReorderErrorCode::ORDER_NOT_FOUND;
            result.message = "订单无效或不存在";
            logOperation("重新下单", QString("订单验证失败，订单ID: %1").arg(originalOrder.id));
            m_isProcessing = false;
            emit reorderFailed(originalOrder.id, result.message);
            return result;
        }
        
        // 3. 批量验证订单项
        result.totalItems = originalOrder.items.size();
        QList<ItemValidationResult> validationResults = validateOrderItems(originalOrder.items);
        
        if (m_isCancelled) {
            result.errorCode = ReorderErrorCode::SYSTEM_ERROR;
            result.message = "操作已取消";
            m_isProcessing = false;
            return result;
        }
        
        // 4. 分析验证结果
        result = analyzeValidationResults(validationResults);
        result.processTime = QDateTime::currentDateTime();
        
        // 5. 更新统计信息
        updateProcessingStatistics(result);
        
        // 6. 记录操作日志
        logOperation("重新下单", QString("完成处理，订单ID: %1, 成功率: %2%")
                    .arg(originalOrder.id).arg(result.getSuccessRate() * 100, 0, 'f', 1));
        
        emit reorderCompleted(result);
        
    } catch (const std::exception& e) {
        result.errorCode = ReorderErrorCode::SYSTEM_ERROR;
        result.message = QString("处理异常: %1").arg(e.what());
        logOperation("重新下单", QString("异常: %1").arg(e.what()));
        emit reorderFailed(originalOrder.id, result.message);
    }
    
    m_isProcessing = false;
    return result;
}

ItemValidationResult ReorderService::validateOrderItem(const OrderItem& item)
{
    ItemValidationResult result;
    result.requestedQuantity = item.quantity;
    
    try {
        // 获取当前菜品信息
        MenuItem menuItem = getCachedMenuItem(item.menuItemId);
        if (menuItem.id.isEmpty()) {
            // 从MenuManager获取最新信息
            auto allMenuItems = m_menuManager->getAllMenuItems();
            bool found = false;
            for (const auto& mi : allMenuItems) {
                if (mi.id == item.menuItemId) {
                    menuItem = mi;
                    found = true;
                    cacheMenuItem(menuItem);
                    break;
                }
            }
            
            if (!found) {
                result.isAvailable = false;
                result.hasStock = false;
                result.availableQuantity = 0;
                result.errorMessage = QString("菜品 \"%1\" 已下架或不存在").arg(item.menuItemName);
                return result;
            }
        }
        
        result.currentItem = menuItem;
        result.isAvailable = true;
        
        // 检查库存
        if (menuItem.stock <= 0) {
            result.hasStock = false;
            result.availableQuantity = 0;
            result.errorMessage = QString("菜品 \"%1\" 暂时缺货").arg(menuItem.name);
        } else {
            result.hasStock = true;
            result.availableQuantity = qMin(item.quantity, menuItem.stock);
            
            if (result.availableQuantity < item.quantity) {
                result.errorMessage = QString("菜品 \"%1\" 库存不足，请求: %2, 可用: %3")
                                    .arg(menuItem.name)
                                    .arg(item.quantity)
                                    .arg(result.availableQuantity);
            }
        }
        
    } catch (const std::exception& e) {
        result.isAvailable = false;
        result.hasStock = false;
        result.availableQuantity = 0;
        result.errorMessage = QString("验证菜品时发生异常: %1").arg(e.what());
    }
    
    return result;
}

QList<ItemValidationResult> ReorderService::validateOrderItems(const QList<OrderItem>& items)
{
    QList<ItemValidationResult> results;
    
    for (int i = 0; i < items.size(); ++i) {
        if (m_isCancelled) {
            break;
        }
        
        const OrderItem& item = items[i];
        ItemValidationResult validation = validateOrderItem(item);
        results.append(validation);
        
        // 发送进度更新信号
        emit progressUpdated(i + 1, items.size(), item.menuItemName);
        
        // 处理批次间隔，避免过度占用CPU
        if ((i + 1) % m_batchSize == 0) {
            QCoreApplication::processEvents();
            QThread::msleep(1); // 短暂延迟
        }
    }
    
    emit validationCompleted(results);
    return results;
}

void ReorderService::processReorderAsync(const Order& originalOrder, const QString& currentUserId)
{
    // 在这个简化版本中，我们直接调用同步方法
    // 在实际应用中，可以使用QThread或QConcurrent进行异步处理
    ReorderResult result = processReorder(originalOrder, currentUserId);
    Q_UNUSED(result); // 结果通过信号发送
}

void ReorderService::cancelCurrentProcessing()
{
    QMutexLocker locker(&m_mutex);
    m_isCancelled = true;
    logOperation("取消", "用户取消当前重新下单操作");
}

QHash<QString, QVariant> ReorderService::getProcessingStatistics() const
{
    QMutexLocker locker(&m_statisticsMutex);
    
    QHash<QString, QVariant> stats;
    stats["totalProcessedOrders"] = m_totalProcessedOrders;
    stats["totalSuccessfulOrders"] = m_totalSuccessfulOrders;
    stats["totalPartialOrders"] = m_totalPartialOrders;
    stats["totalFailedOrders"] = m_totalFailedOrders;
    
    double successRate = m_totalProcessedOrders > 0 ? 
        (double)(m_totalSuccessfulOrders + m_totalPartialOrders) / m_totalProcessedOrders * 100 : 0;
    stats["successRate"] = successRate;
    
    stats["lastProcessTime"] = m_lastProcessTime;
    stats["cacheSize"] = m_menuItemCache.size();
    stats["isProcessing"] = m_isProcessing;
    
    return stats;
}

void ReorderService::resetStatistics()
{
    QMutexLocker locker(&m_statisticsMutex);
    
    m_totalProcessedOrders = 0;
    m_totalSuccessfulOrders = 0;
    m_totalPartialOrders = 0;
    m_totalFailedOrders = 0;
    m_lastProcessTime = QDateTime();
    
    logOperation("统计", "统计信息已重置");
}

void ReorderService::clearCache()
{
    QMutexLocker locker(&m_cacheMutex);
    
    m_menuItemCache.clear();
    m_cacheTimestamps.clear();
    
    logOperation("缓存", "缓存已清空");
}

bool ReorderService::validateUserPermission(const Order& originalOrder, const QString& currentUserId)
{
    if (currentUserId.isEmpty()) {
        return false;
    }
    
    // 检查订单是否属于当前用户
    if (originalOrder.customerId != currentUserId) {
        // 允许整数类型的用户ID比较（向前兼容）
        bool ok;
        int intUserId = currentUserId.toInt(&ok);
        if (ok && originalOrder.customerId == QString::number(intUserId)) {
            return true;
        }
        return false;
    }
    
    return true;
}

bool ReorderService::validateOrderValidity(const Order& order)
{
    return order.isValid() && !order.items.isEmpty();
}

MenuItem ReorderService::getCachedMenuItem(const QString& itemId)
{
    QMutexLocker locker(&m_cacheMutex);
    
    if (!m_cacheEnabled) {
        return MenuItem(); // 返回无效对象
    }
    
    if (m_menuItemCache.contains(itemId)) {
        // 检查缓存是否过期
        QDateTime cacheTime = m_cacheTimestamps.value(itemId);
        if (cacheTime.addSecs(m_cacheTimeoutMinutes * 60) > QDateTime::currentDateTime()) {
            return m_menuItemCache.value(itemId);
        } else {
            // 缓存过期，移除
            m_menuItemCache.remove(itemId);
            m_cacheTimestamps.remove(itemId);
        }
    }
    
    return MenuItem(); // 返回无效对象
}

void ReorderService::cacheMenuItem(const MenuItem& item)
{
    QMutexLocker locker(&m_cacheMutex);
    
    if (!m_cacheEnabled || item.id.isEmpty()) {
        return;
    }
    
    m_menuItemCache[item.id] = item;
    m_cacheTimestamps[item.id] = QDateTime::currentDateTime();
}

QString ReorderService::generateValidationError(const OrderItem& item, const MenuItem& menuItem)
{
    if (menuItem.id.isEmpty()) {
        return QString("菜品 \"%1\" 已下架或不存在").arg(item.menuItemName);
    }
    
    if (menuItem.stock <= 0) {
        return QString("菜品 \"%1\" 暂时缺货").arg(menuItem.name);
    }
    
    if (menuItem.stock < item.quantity) {
        return QString("菜品 \"%1\" 库存不足，需要: %2, 可用: %3")
               .arg(menuItem.name).arg(item.quantity).arg(menuItem.stock);
    }
    
    return "";
}

double ReorderService::calculateTotalAmount(const QList<ItemValidationResult>& validationResults)
{
    double total = 0.0;
    
    for (const auto& result : validationResults) {
        if (result.isValid() && result.availableQuantity > 0) {
            total += result.currentItem.price * result.availableQuantity;
        }
    }
    
    return total;
}

ReorderResult ReorderService::analyzeValidationResults(const QList<ItemValidationResult>& validationResults)
{
    ReorderResult result;
    result.totalItems = validationResults.size();
    result.validationResults = validationResults;
    
    for (const auto& validation : validationResults) {
        if (validation.isCompletelyUnavailable()) {
            result.failedItems++;
            result.unavailableItems.append(validation.currentItem.name.isEmpty() ? 
                "未知菜品" : validation.currentItem.name);
        } else if (validation.canAddPartially()) {
            result.partialItems++;
            result.insufficientItems.append(validation.currentItem.name);
            result.successItemsDetails.append(QString("%1 x %2 (部分)")
                .arg(validation.currentItem.name).arg(validation.availableQuantity));
        } else if (validation.isValid()) {
            result.successItems++;
            result.successItemsDetails.append(QString("%1 x %2")
                .arg(validation.currentItem.name).arg(validation.availableQuantity));
        } else {
            result.failedItems++;
            result.unavailableItems.append(validation.currentItem.name.isEmpty() ? 
                "未知菜品" : validation.currentItem.name);
        }
    }
    
    // 计算总金额
    result.totalAmount = calculateTotalAmount(validationResults);
    
    // 判断整体结果
    if (result.hasAnySuccess()) {
        result.isSuccess = true;
        result.errorCode = ReorderErrorCode::SUCCESS;
        result.message = result.generateUserMessage();
    } else {
        result.isSuccess = false;
        result.errorCode = ReorderErrorCode::ALL_ITEMS_UNAVAILABLE;
        result.message = "所有菜品都无法添加到购物车";
    }
    
    return result;
}

void ReorderService::updateProcessingStatistics(const ReorderResult& result)
{
    QMutexLocker locker(&m_statisticsMutex);
    
    m_totalProcessedOrders++;
    m_lastProcessTime = QDateTime::currentDateTime();
    
    if (result.isCompleteSuccess()) {
        m_totalSuccessfulOrders++;
    } else if (result.isPartialSuccess()) {
        m_totalPartialOrders++;
    } else {
        m_totalFailedOrders++;
    }
}

void ReorderService::logOperation(const QString& operation, const QString& details)
{
    QString logMessage = QString("[ReorderService] %1: %2").arg(operation).arg(details);
    qDebug() << logMessage;
    
    if (m_errorHandler) {
        m_errorHandler->logMessage(ErrorLevel::INFO, logMessage);
    }
}

void ReorderService::onMenuItemUpdated(const MenuItem& item)
{
    QMutexLocker locker(&m_cacheMutex);
    
    if (m_cacheEnabled && m_menuItemCache.contains(item.id)) {
        // 更新缓存中的菜品信息
        m_menuItemCache[item.id] = item;
        m_cacheTimestamps[item.id] = QDateTime::currentDateTime();
    }
}

void ReorderService::onStockUpdated(const QString& itemId, int oldStock, int newStock)
{
    Q_UNUSED(oldStock)
    
    QMutexLocker locker(&m_cacheMutex);
    
    if (m_cacheEnabled && m_menuItemCache.contains(itemId)) {
        // 更新缓存中的库存信息
        m_menuItemCache[itemId].stock = newStock;
        m_cacheTimestamps[itemId] = QDateTime::currentDateTime();
    }
}

void ReorderService::onCacheCleanupTimer()
{
    QMutexLocker locker(&m_cacheMutex);
    
    QDateTime now = QDateTime::currentDateTime();
    QStringList expiredKeys;
    
    for (auto it = m_cacheTimestamps.begin(); it != m_cacheTimestamps.end(); ++it) {
        if (it.value().addSecs(m_cacheTimeoutMinutes * 60) <= now) {
            expiredKeys.append(it.key());
        }
    }
    
    for (const QString& key : expiredKeys) {
        m_menuItemCache.remove(key);
        m_cacheTimestamps.remove(key);
    }
    
    if (!expiredKeys.isEmpty()) {
        logOperation("缓存清理", QString("清理了 %1 个过期缓存项").arg(expiredKeys.size()));
    }
}

} // namespace RestaurantSystem
